package com.sub.spark.streaming.instance;

import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) {
        try {
            // 创建服务器端的ServerSocket，监听端口号1234
            ServerSocket serverSocket = new ServerSocket(1234);
            System.out.println("服务器启动，等待客户端连接...");

            // 服务器端无限循环，等待客户端连接
            while (true) {
                // 等待客户端连接
                Socket socket = serverSocket.accept();
                System.out.println("客户端已连接");

                // 获取输入流和输出流
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

                // 读取客户端发送的消息
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    System.out.println("客户端说：" + inputLine);

                    // 向客户端发送消息
                    out.println("服务器收到你的消息：" + inputLine);
                }

                // 关闭连接
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
